import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../services/yh_info_manger.dart';
import '../../models/yh_info_model.dart';
import '../../manger/network_utils.dart';
import '../../models/user_info_model.dart';
import '../../components/toast_utils.dart';
import '../../manger/user_manger.dart';
import '../../login/controller/login_view.dart';
import '../../services/number_utils.dart';

DateTime? _lastExecutionTime; // 保存上次执行时间

class DetailPopCouponView extends StatelessWidget {
  final VoidCallback onClose;
  final VoidCallback? onRefresh;
  const DetailPopCouponView({Key? key, required this.onClose, this.onRefresh}) : super(key: key);

  void _handleCouponAction(List<CouponDeListModel>? models, BuildContext context) async {
    // 获取当前时间
    final currentTime = DateTime.now();
    
    // 如果距离上次执行时间小于2秒，则直接返回
    if (_lastExecutionTime != null && currentTime.difference(_lastExecutionTime!).inSeconds < 2) {
      return;
    }

    // 更新最后执行时间为当前时间
    _lastExecutionTime = currentTime;

    if (!UserInfos.shared.token.isNotEmpty) {
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const LoginView()),
      );
      return;
    }

    if (models == null || models.isEmpty) return;
    ToastUtils.showLoadingToast(context);
    
    try {
      // 将模型转换为JSON字符串再解码为字典
      final param = {
        'spuCoupons': models.map((e) => e.toJson()).toList(),
      };
      
      // 发起请求
      final response = await NetworkUtils.post(
        RequestCmd.memberSpuCoupons,
        body: param,
      );
      ToastUtils.dismissLoadingToast();

      final model = PhoneCodeModel.fromJson(response);
      if (model.code == 200) {
        ToastUtils.showCenterToast(context, model.msg ?? '领取成功');
        if (onRefresh != null) onRefresh!();
      } else {
        ToastUtils.showCenterToast(context, model.msg ?? '领取失败');
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
    } finally {
      // 可以在这里添加一些清理工作
    }
  }
  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: Stack(
        children: [
          // 蒙层
          Positioned.fill(
            child: GestureDetector(
              onTap: onClose,
              child: Container(
                color: Colors.black.withValues(alpha: 0.5),
              ),
            ),
          ),
          // 底部白色视图
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              height: 560,
              decoration: const BoxDecoration(
                color: Color(0xFFF9F9F9),
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(15),
                  topRight: Radius.circular(15),
                ),
              ),
              child: Column(
                children: [
                  // 顶部标题栏
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          AppLocalizations.of(context)!.edeemOffer,
                          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                        ),
                        GestureDetector(
                          onTap: onClose,
                          child: Image.asset('assets/images/差.png', width: 22, height: 22),
                        ),
                      ],
                    ),
                  ),
                  // 中间优惠券列表
                  Expanded(
                    child: CouponListItem(context),
                  ),
                  SizedBox(height: 15),
                  // 底部操作按钮
                  Padding(
                    padding: const EdgeInsets.only(left: 15, right: 15, bottom: 15),
                    child: SizedBox(
                      width: MediaQuery.of(context).size.width - 60,
                      height: 38,
                      child: ElevatedButton(
                        onPressed: () {
                          final availableCoupons = CouponInfoManager().couponInfoModel
                              ?.where((coupon) => coupon.receiveStatus == 0)
                              .toList();
                          _handleCouponAction(availableCoupons,context);
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.red,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(19),
                          ),
                        ),
                        child: Text(
                          AppLocalizations.of(context)!.claimAll,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 15,
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(height: 15)
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget CouponListItem(BuildContext context) {
    return ListView.builder(
      itemCount: CouponInfoManager().couponInfoModel?.length ?? 0,
      itemBuilder: (context, index) {
        final coupon = CouponInfoManager().couponInfoModel?[index];
        return Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(15),
          ),
          // color: Color(0xFFF6F6F6),
          margin: EdgeInsets.only(left: 15, right: 15, bottom: 15),
          height: 110,
          child: Stack(
            children: [
              // 背景图片
              Positioned.fill(
                child: Image.asset('assets/images/yhj.png', fit: BoxFit.fill),
              ),
              // 价格标签
              Positioned(
                left: 0,
                top: 25,
                width: MediaQuery.of(context).size.width / 3,
                child: Text(
                  maxLines: 1, 
                  overflow:TextOverflow.visible,
                  textAlign: TextAlign.center,
                  coupon?.type == "1" ? 
                    NumberUtils.formatDecimalValue((coupon?.parvalue ?? 0) * 10): 
                    '${coupon?.symbol}${coupon?.parvalue}',
                  style: TextStyle(
                    fontSize: 22,
                    fontWeight: FontWeight.bold,
                    color: Colors.red,
                    letterSpacing: -0.5,
                  ),
                ),
              ),
              // 使用门槛
              Positioned(
                left: 0,
                top: 60,
                width: MediaQuery.of(context).size.width / 3,
                child: Text(
                  (coupon?.cill ?? 0) > 0
                      ? isChineseLocale()
                          ? '满${coupon?.symbol}${coupon?.cill}可用'
                          : 'Full ${coupon?.symbol}${coupon?.cill}'
                      : AppLocalizations.of(context)!.wumenkan,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.red,
                  ),
                ),
              ),
              // 商品名称
              Positioned(
                left: MediaQuery.of(context).size.width * 0.36,
                top: 18,
                child: Text(
                  coupon?.spuName ?? '',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 15,
                    color: Colors.grey[700],
                  ),
                ),
              ),
              // 有效期
              Positioned(
                left: MediaQuery.of(context).size.width * 0.36,
                top: 45,
                child: Text(
                  isChineseLocale()
                      ? '${AppLocalizations.of(context)!.afterClaiming}: ${coupon?.days}天有效 '
                      : '${coupon?.days} days valid after claim',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
              ),
              // 使用说明
              Positioned(
                left: MediaQuery.of(context).size.width * 0.36,
                top: 70,
                right: 15, // 为右侧按钮留出空间
                child: Text(
                  isChineseLocale()
                      ? '${AppLocalizations.of(context)!.instructions}: ${coupon?.description ?? ''}'
                      : coupon?.description ?? '',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
              ),
               // 已领取标记
              if (coupon?.receiveStatus != 0)
                Positioned(
                  right: 0,
                  top: 0,
                  child: Image.asset(isChineseLocale() ? 'assets/images/已领取.png' : 'assets/images/已领取e.png', width: 65, height: 49),
                ),
              // 领取按钮
              Positioned(
                right: 10,
                top: 38,
                width: 78,
                height: 30,
                child: ElevatedButton(
                  onPressed: () {
                    if (coupon?.receiveStatus == 1) {
                      onClose();
                    } else {
                      final coupons = <CouponDeListModel>[];
                      if (coupon != null) {
                        coupons.add(coupon);
                      }
                      _handleCouponAction(coupons,context);
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: coupon?.receiveStatus == 0 ? Colors.red : Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(17),
                    ),
                    side: BorderSide(color: Colors.red),
                    padding: EdgeInsets.zero, // 移除默认内边距
                    minimumSize: Size.zero, // 移除最小尺寸限制
                    tapTargetSize: MaterialTapTargetSize.shrinkWrap, // 紧凑布局
                  ),
                  child: Text(
                    coupon?.receiveStatus == 0 ? isChineseLocale() ? AppLocalizations.of(context)!.get : 'Claim Now' : AppLocalizations.of(context)!.useNow,
                    style: TextStyle(
                      color: coupon?.receiveStatus == 0 ? Colors.white : Colors.red,
                    ),
                  ),
                ),
              ),
             
            ],
          ),
        );
      },
    );
  }
}
